﻿using System;
using System.Drawing ;
using System.Windows.Forms;
using LayerEntity.Persona;
using LayerEntity.Persona.Clientes;
using LayerEntity.Sistema;
using LayerLogic;

namespace System2012.Persona.Clientes
{
    public partial class Cliente : DevExpress.XtraEditors.XtraForm
    {
        #region Variables
        /// <summary>
        /// Especifica el estado acutal del registro.
        /// Valores: 
        /// 1: Nuevo Cliente
        /// 2: Editando Cliente
        /// </summary>
        int intEditingClient = 0;
        bool moverNextControl = false;
        #endregion
        public Cliente()
        {
            this.InitializeComponent();
            //AgregarEventos(this);
            SystemUtils.RecordManagerPersona.UpdateList += new LayerLogic.Persona.LPersona.AddObject(UpdateGrilla);
            this.NuevoCliente();
            this.TxtBuscar.EditValue = string.Empty;
            this.ucDireccion1.CambiarFoco += new System2012.Persona.UserControls.UCDireccion.UpdateFocus(delegate()
            {
                this.moverNextControl = true;
            });
        }

        #region Metodos

        void VerContactos()
        {
            if (this.gridView1.RowCount > 0)
            {
                IEPersona per = (IEPersona)this.gridView1.GetFocusedRow();
                if (per != null)
                {
                    MantenimientoContactos mc = new MantenimientoContactos(per);
                    mc.ShowDialog();
                    SystemUtils.RecordManagerPersona.AddCliente(per);
                }
            }
            else
            {
                SystemUtils.AlerMessaje("No hay Informacion de Clientes");
            }
        }

        private void NuevoCliente()
        {
            this.TxtCodigo.EditValue = "0";
            this.TxtNumero.EditValue = string.Empty;
            this.txtRSocial.EditValue = string.Empty;
            this.TxtNComercial.EditValue = string.Empty;
            this.ChkIsDeudaConfidencial.Checked = false;
            this.ChkNoCredito.Checked = false;
            this.TxtObservacion.EditValue = string.Empty;
            this.intEditingClient = 1;
            this.ucDireccion1.NewAddress();
        }

        void Editar(IEPersona cli)
        {
            if (cli != null)
            {
                this.CbDocumento.EditValue = cli.IdTipoDocumento;
                this.CbTipo.EditValue = cli.IdTipoCliente;
                this.TxtCodigo.EditValue = cli.IdPersona;
                this.txtRSocial.EditValue = cli.RazonSocial;
                this.TxtNComercial.EditValue = cli.NombreComercial;
                this.CbSexo.EditValue = cli.Sexo;
                this.TxtFechaCumpleanos.EditValue = cli.FechaNacimiento.ToShortDateString();
                this.TxtNumero.EditValue = cli.NumeroDocumento;
                this.ChkIsDeudaConfidencial.Checked = cli.IsDeudaConfidencial;
                this.ChkNoCredito.Checked = cli.CreditoNoDisponible;
                this.intEditingClient = 2;
                this.ucDireccion1.SetDireccion(cli.GetPrincipalAddress());
            }
        }

        private void UpdateGrilla(string msj, LayerLogic.EnumOperaciones op)
        {
            this.RefreshLista();
        }

        void ViewAddress()
        {
            if (this.gridView1.RowCount > 0)
            {
                IEPersona per = (IEPersona)this.gridView1.GetFocusedRow();
                if (per != null)
                {
                    MantenimientoDireccion md = new MantenimientoDireccion(per);
                    md.ShowDialog();
                }
            }
            else
            {
                SystemUtils.AlerMessaje("No hay Registro de Clientes");
            }
        }

        void RefreshLista()
        {
            this.gridControl1.DataSource = SystemUtils.RecordManagerPersona.GetClient();
            this.gridControl1.RefreshDataSource();
        }

        private void SaveCliente()
        {
            bool estado = true ;
            if (this.CbTipo.EditValue == null)
            {
                SystemUtils.AlerMessaje("Seleccione el Tipo de Cliente");
                this.CbTipo.Focus();
                estado = false;
                return;
            }

            if (this.CbDocumento.EditValue == null)
            {
                SystemUtils.AlerMessaje("Seleccione el Tipo de Documento");
                this.CbDocumento.Focus();
                estado = false;
                return;
            }
            if (this.TxtNumero.EditValue.ToString().Trim() == string.Empty)
            {
                SystemUtils.AlerMessaje("Ingrese el Numero de Documento");
                this.TxtNumero.Focus();
                estado = false;
                return;
            }

            if (this.txtRSocial.EditValue.ToString().Trim() == string.Empty)
            {
                SystemUtils.AlerMessaje("Ingrese la Razon Social del Cliente");
                this.txtRSocial.Focus();
                estado = false;
                return;
            }

            if (this.CbSexo.EditValue == null)
            {
                SystemUtils.AlerMessaje("Seleccione el Sexo del Cliente");
                this.CbSexo.Focus();
                estado = false;
                return;
            }
            EDireccion dir = this.ucDireccion1.GetDireccion();
            if (dir == null)
            {
                estado = false;
                return;
            }
            if (estado)
            {
                IEPersona c = ObjectFactoryPersona.CreateClient();
                //c.IdPersona = 0;
                c.CreditoNoDisponible = this.ChkNoCredito.Checked;
                c.FechaNacimiento = Convert.ToDateTime(this.TxtFechaCumpleanos.Text);
                c.IdEstado = 1;
                c.IdTipoCliente = (int)this.CbTipo.EditValue;
                c.IdTipoDocumento = (int)this.CbDocumento.EditValue;
                c.IsDeudaConfidencial = this.ChkIsDeudaConfidencial.Checked;

                c.NombreComercial = this.TxtNComercial.EditValue.ToString();
                c.NumeroDocumento = this.TxtNumero.EditValue.ToString();
                c.Observacion = this.TxtObservacion.EditValue.ToString();
                c.RazonSocial = this.txtRSocial.EditValue.ToString();
                c.Sexo = (int)this.CbSexo.EditValue;
                LayerLogic.EnumOperaciones operacion;
                if (this.intEditingClient == 2)
                {
                    c.IdPersona = this.TxtCodigo.EditValue.ToString();
                    c.TipoPersonaSistema = ((IEPersona)this.gridView1.GetFocusedRow()).TipoPersonaSistema;
                    operacion = EnumOperaciones.Actualizar;
                }
                else
                {
                    c.TipoPersonaSistema = "10000000000000";
                    operacion = EnumOperaciones.Insertar;
                }

                string op = SystemUtils.RecordManagerPersona.SaveClientes(c, operacion);

                if (op != null)
                {
                    c.IdPersona = op.Trim();
                    IEPersona newC = null;
                    if (operacion == EnumOperaciones.Actualizar)
                    {
                        newC = SystemUtils.RecordManagerPersona.GetClient(c);
                    }
                    else
                    {
                        newC = c;
                    }
                    if (newC != null)
                    {
                        if (op != "")
                        {
                            dir.IdPersona = op.Trim();
                            dir.IsPrincipal = true;
                            int address = SystemUtils.RecordManagerPersona.SaveAddress(dir, this.ucDireccion1.Operacion);
                            if (address > 0)
                            {
                                newC.AddAddressInfo(dir);
                                SystemUtils.InformationMessaje("Cliente Registrado.");
                            }
                            else
                            {
                                SystemUtils.ShowMessaje("Cliente Registrado, Pero la Direccion Fallo.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            SystemUtils.RecordManagerPersona.AddCliente(newC);
                            this.NuevoCliente();
                        }
                    }
                }
            }
        }

        #endregion

        private void ClickButton(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (e.Item.Tag != null)
            {
                if ((string)e.Item.Tag == "NuevoCliente")
                {
                    this.NuevoCliente();
                }
                if ((string)e.Item.Tag == "Cancel")
                {
                    if (SystemUtils.Question("Desea Cancelar", this.Text) == DialogResult.Yes)
                    {
                        this.Close();
                    }
                }
                if ((string)e.Item.Tag == "Guardar")
                {
                    this.SaveCliente();
                }
                if (e.Item.Tag.ToString().Equals("Contacto"))
                {
                    this.VerContactos();
                }
                if ((string)e.Item.Tag == "LoadAll")
                {
                    this.loadAll = 1;
                    if (!this.BGWLoadClientes.IsBusy)
                    {
                        this.BGWLoadClientes.RunWorkerAsync();
                    }
                }
                if ((string)e.Item.Tag == "Exportar")
                {
                    if (this.gridView1.RowCount > 0)
                    {
                        SystemUtils.Exportar("Clientes", this.gridControl1);
                    }
                    else
                    {
                        SystemUtils.AlerMessaje("No hay Datos a Exportar");
                    }
                }

                if ((string)e.Item.Tag == "VerDirecciones")
                {
                    this.ViewAddress();
                }
                if ((string)e.Item.Tag == "ConvertToEmployee")
                {
                    IEPersona per = ObjectFactoryPersona.ConvertTo((IEPersona)this.gridView1.GetFocusedRow(), EnumTipoPersona.Empleado);
                    if (per != null)
                    {
                        if (SystemUtils.RecordManagerPersona.SaveEmpleado(per, EnumOperaciones.Actualizar) != string.Empty)
                        {
                            SystemUtils.RecordManagerPersona.AddEmpleado(per);
                        }
                    }
                }
                if ((string)e.Item.Tag == "ConvertToSupplier")
                {
                    IEPersona per = ObjectFactoryPersona.ConvertTo((IEPersona)this.gridView1.GetFocusedRow(), EnumTipoPersona.Proveedor);
                    if (per != null)
                    {
                        if (SystemUtils.RecordManagerPersona.SaveProveedores(per, EnumOperaciones.Actualizar) != "")
                        {
                            SystemUtils.RecordManagerPersona.AddProveedor(per);
                        }
                    }
                }
            }
        }
        
        private void Cliente_Load(object sender, EventArgs e)
        {
            this.Size = new System.Drawing.Size(this.MdiParent.Size.Width,this.MdiParent.Size.Height);
            this.Location = new System.Drawing.Point(this.MdiParent.Location.X, this.MdiParent.Location.Y);
            this.intListaCargar = 1;
            this.BGWLoadList.RunWorkerAsync();
            this.BGWLoadClientes.RunWorkerAsync();
            this.TxtFechaCumpleanos.EditValue = DateTime.Now.Date;
            this.CbTipo.Focus();
        }
        
        #region Procesos BackGround
        /// <summary>
        /// Indica que lista es la que se esta cargando actualmente
        /// Valores: 
        /// 1.- Tipo de Clientes
        /// 2.- Documentos 
        /// 3.- Sexo
        /// </summary>
        int intListaCargar = 0;
        private void BgwLoadListDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //Recupera los tipos de clientes
            if (this.intListaCargar == 1)
            {
                this.BGWLoadList.ReportProgress(30, "Load Tipos de Clientes");
                e.Result = SystemUtils.RecordManagerCommonList.GetTipoClientes();
                this.BGWLoadList.ReportProgress(100, "Load Complete");
            }

            //cargamos los documentos
            if (this.intListaCargar == 2)
            {
                this.BGWLoadList.ReportProgress(30, "Load Documentos");
                e.Result = SystemUtils.RecordManagerCommonList.GetDocument(0);
                this.BGWLoadList.ReportProgress(100, "Load Complete");
            }

            //cargamos los Sexos
            if (this.intListaCargar == 3)
            {
                this.BGWLoadList.ReportProgress(30, "Load Sexos");
                e.Result = SystemUtils.RecordManagerPersona.GetSexos();
                this.BGWLoadList.ReportProgress(100, "Load Complete");
            }
        }

        private void BgwLoadListProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            this.lblStatus.Caption = e.UserState.ToString();
        }

        private void BgwLoadListRunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (this.intListaCargar == 3)
            {
                this.CbSexo.Properties.DataSource = e.Result;
            }
            if (this.intListaCargar == 2)
            {
                this.CbDocumento.Properties.DataSource = e.Result;
                this.intListaCargar = 3;
                this.BGWLoadList.RunWorkerAsync();
            }
            if (this.intListaCargar == 1)
            {
                this.CbTipo.Properties.DataSource = e.Result;
                this.intListaCargar = 2;
                this.BGWLoadList.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Indica si se carga todos los datos de los clientes
        /// </summary>
        int loadAll = 0;
        private void BgwLoadClientesDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            this.BGWLoadClientes.ReportProgress(30, "Load Clientes");
            if (this.loadAll == 0)
            { 
                SystemUtils.RecordManagerPersona.GetClient(100);  
            }
            else
            {
                SystemUtils.RecordManagerPersona.GetClient(0);
            }
            this.BGWLoadClientes.ReportProgress(100, "Load Complete");
        }

        private void BgwLoadClientesRunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.RefreshLista();
            if (loadAll != 0)
            {
                SystemUtils.InformationMessaje("Proceso Completado");
            }
        }

        private void BgwLoadClientesProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            this.lblStatus.Caption = e.UserState.ToString();
        }

        #endregion

        private void GridView1FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            this.Editar((IEPersona)this.gridView1.GetFocusedRow());
        }

        private void CustomText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.Name == "gcTipoDocumento")
            { 
                object obj = this.gridView1.GetRowCellValue(e.RowHandle, this.gcIdTipoDocumento);
                if (obj != null)
                {
                    EDocumento doc = SystemUtils.RecordManagerCommonList.GetDocument(Convert.ToInt64(obj.ToString()));
                    if (doc != null)
                    {
                        e.DisplayText = doc.Abreviatura ;
                    }
                }
            }
            if (e.Column.Name == "gcSexo")
            {
                //gcSexo
                //gcIdSexo
                object obj = this.gridView1.GetRowCellValue(e.RowHandle, this.gcIdSexo);
                if (obj != null)
                {
                    ESexo s = SystemUtils.RecordManagerPersona.GetSexos(Convert.ToInt32(obj.ToString()));
                    if (s != null)
                    {
                        e.DisplayText = s.Descripcion;
                    }
                }
            }
            if (e.Column.Name == "gcEstado")
            {
                object obj = this.gridView1.GetRowCellValue(e.RowHandle, this.gcIdEstado);
                if (obj != null)
                {
                    EEstado est = SystemUtils.RecordManagerCommonList.GetEstadoById(Convert.ToInt32(obj.ToString()));
                    if (est != null)
                    {
                        e.DisplayText = est.Descripcion;
                    }
                }
            }
            if (e.Column.Name == "gcTipoCliente")
            {
                //gcTipoCliente
                //gcIdTipoCliente
                object obj = this.gridView1.GetRowCellValue(e.RowHandle, this.gcIdTipoCliente);
                if (obj != null)
                {
                    ETipoCliente t = SystemUtils.RecordManagerCommonList.GetClientType(Convert.ToInt32(obj.ToString()));
                    if (t != null)
                    {
                        e.DisplayText = t.Descripcion;
                    }
                }
            }
        }

        private void CambiandoDescripcion(object sender, EventArgs e)
        {
            this.gridControl1.DataSource = SystemUtils.RecordManagerPersona.GetClient(this.TxtBuscar.EditValue.ToString(), "rs_persona");
            this.gridControl1.RefreshDataSource();
        }

        private void GridView1Click(object sender, EventArgs e)
        {
            this.Editar((IEPersona)this.gridView1.GetFocusedRow());
        }

        private void SelectNextControl(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Right || e.KeyCode == Keys.Down)
            {
                if (sender == this.CbTipo || sender == this.CbDocumento || sender == this.TxtNumero || sender == this.txtRSocial ||
                    sender == this.TxtNComercial || sender == this.CbSexo)
                {
                    SendKeys.Send("{TAB}");
                }
                if (sender == this.TxtFechaCumpleanos)
                {
                    this.ucDireccion1.SetFocus(false);
                }
            }
            if (e.KeyCode == Keys.Left)
            {
                this.ChkIsDeudaConfidencial.Focus();
            }
            if (e.KeyCode == Keys.Up)
            {
                if (this.moverNextControl)
                {
                    this.TxtFechaCumpleanos.Focus();
                    this.moverNextControl = false;
                    //e.Handled = true;
                }
                else
                {
                    if (this.ChkNoCredito == sender)
                    {
                        this.ucDireccion1.SetFocus(true);
                    }
                    else
                    {
                        this.SelectNextControl((System.Windows.Forms.Control)sender, false, true, true, true);
                    }
                }
                //if (sender == TxtObservacion) {
                // //   ChkIsDeudaConfidencial.Focus();
                //    SelectNextControl((System.Windows.Forms.Control)sender, false, true, true, true);
                //}
                //if (sender == ChkIsDeudaConfidencial)
                //{
                //    ChkNoCredito.Focus();
                //}
                //if (ChkNoCredito == sender)
                //{
                //    ucDireccion1.SetFocus(true);
                //}
                //if (TxtFechaCumpleanos == sender)
                //{
                //    CbSexo.Focus();
                //}
                //if (CbSexo == sender)
                //{
                //    TxtNComercial.Focus();
                //}
                //if (TxtNComercial == sender)
                //{
                //    txtRSocial.Focus();
                //}
                //if (txtRSocial == sender)
                //{
                //    TxtNumero.Focus();
                //}
                //if (TxtNumero == sender)
                //{
                //    CbDocumento.Focus();
                //}
                //if (CbDocumento == sender)
                //{
                //    CbTipo.Focus();
                //}
                ////moverNextControl = false;
            }
        }

        //moverNextControl = false;
        
        public void AgregarEventos(Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c.HasChildren)
                {
                    this.AgregarEventos(c);
                }
                c.KeyDown += new KeyEventHandler(SelectNextControl);
            }
        }

        private void GridView1MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (this.gridView1.GetFocusedRow() != null)
                {
                    this.popupMenu1.ShowPopup(new Point(MousePosition.X, MousePosition.Y));
                }
            }
        }
    }
}